package com.hs.order.exception;

import com.hs.common.api.dto.ResultCode;
import com.hs.common.api.dto.ResultVo;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Bai Dingkun
 * @date 2022-07-13
 * @desc
 */
@RestControllerAdvice
public class GlobalException {

    /**
     * 参数异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo getMethodArgumentNotValidException(MethodArgumentNotValidException e){

        e.printStackTrace();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
//        收集错误信息
        Map<String, String> msg = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));

        return new ResultVo(ResultCode.PARAM_IS_BLANK,msg);

    }

    @ExceptionHandler(BusinessException.class)
    public ResultVo getBusinessException(BusinessException e){

        e.printStackTrace();
        return new ResultVo(ResultCode.FAILED,e.getMessage());

    }

    @ExceptionHandler(Exception.class)
    public ResultVo getException(Exception e){

        e.printStackTrace();
        return new ResultVo(ResultCode.FAILED);

    }

}
